package admin

import (
	"gin-base/base/config"
	"gin-base/base/db"
	"gin-base/common/utils"
	"github.com/jinzhu/gorm"
)

type Admin struct {
	AuthKey  string `gorm:"size:255"` // Default size for string is 255, reset it with this tag
	Avatar   string `gorm:"size:255"` // Default size for string is 255, reset it with this tag
	Username string `gorm:"size:255"` // Default size for string is 255, reset it with this tag
	Name     string `gorm:"size:255"` // Default size for string is 255, reset it with this tag
	Email    string `gorm:"size:255"` // Default size for string is 255, reset it with this tag
	Password string `gorm:"size:255"` // Default size for string is 255, reset it with this tag
	Status   int
	gorm.Model
}

func (Admin) TableName() string {
	return config.Ini.String("mysql.table_prefix") + "admin"
}

func Login(username string, password string) interface{} {
	db := db.Open()
	defer db.Close()

	user := []Admin{}

	db.Where("username = ? AND password = ?", username, utils.Md5(password)).First(&user)
	if len(user) == 0 {
		return nil
	}

	return user[0]
}

func LoginByAuthKey(authKey string) Admin {
	db := db.Open()
	defer db.Close()

	user := []Admin{}

	db.Where("auth_key = ?", authKey).First(&user)

	if len(user) == 0 {
		return Admin{}
	}
	return user[0]
}
